#!/bin/sh
umask 0022

# Defaults
keep="n"
CONFDIR="/etc/mkinitramfs"
verbose="n"
errors_to="2>/dev/null"

while getopts "d:ko:r:" flag; do
	case $flag in
	d)
		CONFDIR="${OPTARG}"
		if [ ! -d "${CONFDIR}" ]; then
			echo "${0}: ${CONFDIR}: Not a directory" >&2
			exit 1
		fi
		;;
	o)
		touch ${OPTARG}
		outfile="$(readlink -f ${OPTARG})"
		;;
	k)
		keep="y"
		;;
	esac
done

shift $((${OPTIND} - 1))

# For dependency ordered mkinitramfs hook scripts.
. /usr/share/initramfs-tools/scripts/functions
. /usr/share/initramfs-tools/hook-functions

. ${CONFDIR}/initramfs.conf

EXTRA_CONF=''
for i in ${CONFDIR}/conf.d/*; do
	EXTRA_CONF="${EXTRA_CONF} $(basename $i | grep '^[a-z0-9][a-z0-9\._-]*$' | grep -v '\.dpkg-.*$')";
done
for i in ${EXTRA_CONF}; do
. ${CONFDIR}/conf.d/${i}
done

if [ x${outfile} = x ]; then
	usage
fi

if [ -d ${outfile} ]; then
	echo "${outfile} is a directory"
	exit 1
fi

DESTDIR=$(mktemp -t -d mkinitramfs_XXXXXX) || exit 1
__TMPCPIOGZ=$(mktemp -t mkinitramfs-OL_XXXXXX) || exit 1

#
# Export environment for hook scripts.
#

export version
export CONFDIR
export DESTDIR
export __TMPCPIOGZ

for d in usr/bin /usr/lib dev bin /usr/bin etc sbin lib/modules proc; do
    mkdir -p ${DESTDIR}/${d}
done

# Copy device files
cp -av /dev/* ${DESTDIR}/dev/

# Copy configdirectory
cp -av ${CONFDIR}/etc ${DESTDIR}

# Have to do each file, because cpio --dereference doesn't recurse down
# symlinks.

#ln -s /usr/lib/klibc/bin/* ${DESTDIR}/bin
#ln -s /lib/klibc-*.so ${DESTDIR}/lib

copy_exec /usr/share/initramfs-tools/init /init

BUSYBIN="/root/busybox-1.4.2/busybox"
# Busybox

copy_exec ${BUSYBIN} /bin
# Necessary to run /init
ln -s ${DESTDIR}/bin/busybox ${DESTDIR}/bin/sh

# Partitioning and disk tools
copy_exec /sbin/grub /sbin
copy_exec /sbin/cfdisk /sbin
copy_exec /sbin/sfdisk /sbin

# Hardware diagnosis detection
copy_exec /sbin/sysctl /sbin
copy_exec /usr/bin/lshw /bin

# Network Utilities
copy_exec /sbin/mii-tool /sbin
copy_exec /usr/sbin/ethtool /sbin
copy_exec /usr/sbin/tcpdump /sbin

# Debugging
copy_exec /usr/bin/strace /sbin

# Kernel Modules
copy_exec /sbin/modprobe /sbin
copy_exec /sbin/depmod /sbin
copy_exec /sbin/rmmod /sbin

# Pretty Screen Stuff
copy_exec /usr/bin/pv /sbin

# Network utilies
copy_exec /usr/sbin/ntpdate /sbin
copy_exec /usr/bin/curl /bin
copy_exec /usr/bin/rsync /bin

# Name lookkup
cp -av /lib/libns* ${DESTDIR}/lib

# Ruby
copy_exec /usr/bin/ruby /usr/bin
cp -av /usr/lib/ruby ${DESTDIR}/usr/lib

(cd ${DESTDIR} && find . | cpio -v --dereference -o -H newc | gzip -9 >${outfile})

if [ -s ${__TMPCPIOGZ} ]; then
    cat ${__TMPCPIOGZ} >>${outfile}
fi

if [ "${keep}" = "y" ]; then
	echo "Working files in ${DESTDIR} and overlay in ${__TMPCPIOGZ}"
else
	rm -rf "${DESTDIR}"
	rm -rf "${__TMPCPIOGZ}"
fi

exit 0
